<template>
  <div class="data-sql-container">
    <div class="left">
      <div class="left-title">数据表</div>
      <div class="left-select-box">
        <a-select
          v-model="dataSource"
          @change="dataSourceChange"
          placeholder="请选择数据源"
          :options="dataSourceOptions"
        >
        </a-select>

        <a-input v-model="tableSearch" :disabled="dataSource === undefined" placeholder="搜索指定数据表" />

        <a-icon type="redo" class="icon1" title="刷新" @click="loadDataSourceOptions" />
        <!-- <a-icon type="search" class="icon2" title="搜索"/> -->
      </div>

      <div class="table-list">
        <template v-for="(item, index) in tableArr">
          <div
            :class="['table-item']"
            :key="index"
            :title="item.tableName"
            v-if="item.tableName.indexOf(tableSearch) > -1"
            @click="tableListSelect(item)"
          >
            <p>{{ item.tableName }}</p>
          </div>
        </template>
      </div>
    </div>
    <div class="right">
      <div class="operate-box">
          <SQLEditor ref="SQLEditor" :sqlString="sqlString"/>
      </div>

      <div class="info-box" v-if="dataSource !== undefined">
        <span>数据库类型:</span>{{ dataSourceType }} <span>数据源地址:</span>{{ dataSourceUrl }}
      </div>
    </div>
  </div>
</template>

<script>
import SQLEditor from '@/components/SQLEditor'
export default {
  name: 'CreateIndexByDataSql',
  components: { SQLEditor },
  data() {
    return {
      dataSourceOptions: [],
      dataSource: undefined,
      tableSearch: '',
      dataSourceName: '',
      dataSourceType: '',
      dataSourceUrl: '',
      searchFlag: false,
      tableArr: [],
      operateTbaleIdArr: [],
      sqlString: ''
    }
  },
  mounted() {
    this.loadDataSourceOptions()
  },

  methods: {
    // 加载数据源下拉项
    loadDataSourceOptions() {
      this.dataSourceOptions = []
      this.$get('/sys/dataSource/list?pageNo=1&pageSize=1000').then((res) => {
        res.result.records.map((item) => {
          if (item.dbStatus === '1') {
            item.value = item.code
            item.title = item.name
            this.dataSourceOptions.push(item)
          }
        })

        if (this.dataSourceOptions.length === 0) {
          this.$message.warning(`数据源列表为空，请先行维护`)
        } else {
          // 默认选中第一个数据源
          if (this.dataSource === undefined) {
            this.dataSource = this.dataSourceOptions[0].value
            this.dataSourceChange(this.dataSourceOptions[0].value, {
              data: {
                props: this.dataSourceOptions[0]
              }
            })
          }
        }
      })
    },
    // 切换数据源
    dataSourceChange(value, options) {
      this.tableSearch = ''
      this.$refs.SQLEditor.handleEmptySqlContent()
      this.dataSourceName = options.data.props.name
      this.dataSourceType = options.data.props.dbType_dictText
      this.dataSourceUrl = options.data.props.dbUrl
      this.$get(`/index/config/listTables?code=${value}`).then((res) => {
        this.tableArr = res.result
      })
    },
    // 选择数据表
    tableListSelect(table) {
      if (this.$refs.SQLEditor.sqlContent) {
        this.$refs.SQLEditor.handleInsertToValue(table.tableName)
      } else {
        this.$refs.SQLEditor.handleInsertToValue('select ' + table.tableName + '.* from ' + table.tableName)
      }
    },
    checkSql() {
      this.sqlString = this.$refs.SQLEditor.handleReturnValue()
      if (this.sqlString.trim() === '') {
        this.$message.warning(`SQL语句不能为空`)
        return
      }

      this.$post('/index/config/getSqlColumns', {
        dataSource: this.dataSource,
        // 替换格式化sql语句产生的回车符
        sql: this.sqlString.replace(/\n/g, ' ')
      }).then(res => {
        if (res.success) {
          const indexArr = []
          res.result.map(item => {
            const column = {
              dataSource: this.dataSource,
              dataSourceName: this.dataSourceName,
              columnId: item.id,
              columnLength: item.columnLength,
              scale: item.scale,
              dataType: item.dataType,
              groupType: 'avg',
              isPercent: false,
              labels: '',
              name: item.tableColumn,
              remark: '',
              isDate: 0,
              dimensionType: undefined,
              dimensionTypeTime: undefined,
              tableColumn: item.tableColumn,
              tableName: item.tableName,
              unit: '',
              type: 0
            }

            indexArr.push(column)
          })

          this.$emit('ok', {
            indexArr,
            dataSource: this.dataSource,
            sqlData: {
              dataSource: this.dataSource,
              sql: this.sqlString.replace(/\n/g, ' ')
            }
          })
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.data-sql-container {
  height: calc(100%);
  display: flex;
  justify-content: center;
  user-select: none;

  & > .left {
    width: 250px;
    height: 100%;
    background: #fafafa;
    border-bottom: 4px solid #ffffff;

    & > .left-title {
      height: 36px;
      line-height: 36px;
      font-size: 15px;
      color: #000022;
      text-align: center;
      background-color: #eff4f9;
    }

    & > .left-select-box {
      position: relative;
      padding: 10px;
      border-bottom: 4px solid #ffffff;

      .ant-select {
        width: 200px;
        margin-bottom: 10px;
      }

      & > .ant-input {
        width: 200px;
      }

      .icon1 {
        position: absolute;
        width: 20px;
        height: 32px;
        font-size: 20px;
        top: 10px;
        right: 10px;
        cursor: pointer;
        line-height: 35px;
      }

      .icon2 {
        position: absolute;
        width: 20px;
        height: 32px;
        font-size: 22px;
        top: 53px;
        right: 10px;
        cursor: pointer;
        line-height: 35px;
      }
    }

    & > .table-list {
      height: calc(100% - 138px);
      overflow-x: hidden;
      overflow-y: auto;
      padding: 10px 0;

      .table-item {
        cursor: pointer;

        & > p {
          height: 36px;
          line-height: 36px;
          padding: 0 10px;
          margin-bottom: 0;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          border-bottom: 1px dashed #e8e8e8;
        }

        &:hover,
        &.active {
          background-color: #eff4f9;
        }
      }
    }
  }

  & > .right {
    flex: 1;
    width: calc(100% - 275px);
    height: 100%;
    margin-left: 15px;
    background: #fafafa;
    overflow: hidden;
    position: relative;

    & > .operate-box {
      width: 100%;
      height: calc(100% - 40px);
      border-bottom: 4px solid #ffffff;
      overflow: auto;
      position: relative;
    }

    & > .info-box {
      height: 40px;
      line-height: 40px;
      clear: both;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;

      & > span {
        margin: 0 10px;
        font-weight: bold;
      }
    }
  }
}
</style>

<style lang="less">
.data-sql-container {
}
</style>
